package com.nari.ncps.screen.service.impl.al;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.al.AlOpermonEnergyConDjlydl;
import com.nari.ncps.screen.entity.al.AlProdoperPrdQual;
import com.nari.ncps.screen.entity.al.AlProdoperStationPer;
import com.nari.ncps.screen.entity.al.AlProdoperStock;
import com.nari.ncps.screen.mapper.al.AlOpermonEnergyConDjlydlMapper;
import com.nari.ncps.screen.mapper.al.AlProdoperStationPerMapper;
import com.nari.ncps.screen.service.al.AlProdoperStationPerService;
import com.nari.ncps.screen.vo.al.AlProdoperStationPerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 电厂火电占比表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class AlProdoperStationPerServiceImpl extends ServiceImpl<AlProdoperStationPerMapper, AlProdoperStationPer> implements AlProdoperStationPerService {

    @Autowired
    AlOpermonEnergyConDjlydlMapper alOpermonEnergyConDjlydlMapper;

    @Override
    public List<AlProdoperStationPerVO> getPowerStationRatio() {

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取6个月日期
        LocalDate startDate = currentDate.minusMonths(5);
        // 获取当前年月
        String currentYearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        // 获取6月前年月
        String sixagoYearSameMonth = startDate.format(DateTimeFormatter.ofPattern("yyyyMM"));

        // 查询最近6个月的数据
        LambdaQueryWrapper<AlOpermonEnergyConDjlydl> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AlOpermonEnergyConDjlydl::getDateType, 1)
                .in(AlOpermonEnergyConDjlydl::getOrgCode, "134053", "134035")
                .in(AlOpermonEnergyConDjlydl::getPowerGenerationType, "02", "03")
                .between(AlOpermonEnergyConDjlydl::getStatisticTime, sixagoYearSameMonth,currentYearMonth)
                .orderByAsc(AlOpermonEnergyConDjlydl::getStatisticTime);
        List<AlOpermonEnergyConDjlydl> qualList = alOpermonEnergyConDjlydlMapper.selectList(wrapper);

        List<AlProdoperStationPerVO> voList = new ArrayList<>();
        for (AlOpermonEnergyConDjlydl entity : qualList) {
            AlProdoperStationPerVO vo = new AlProdoperStationPerVO();
//            if (qualList.equals(entity.getStatisticTime())) {
                vo.setYear(entity.getYear());
                vo.setMonth(entity.getMonth());
                vo.setHuolinheGreenPower(entity.getElectricityConsumptio());
                vo.setHuolinheFossilPower(entity.getElectricityConsumptio());
                vo.setBaiyinhuaGreenPower(entity.getElectricityConsumptio());
                vo.setBaiyinhuaFossilPower(entity.getElectricityConsumptio());
                vo.setHuolinheGreenRatio(entity.getElectricityConsumptio());
                vo.setBaiyinhuaGreenRatio(entity.getElectricityConsumptio());

                voList.add(vo);
//            }
        }


//        // 获取当前时间并生成前6个月的statistic_time列表
//        LocalDate now = LocalDate.now();
//        List<String> statisticTimes = new ArrayList<>();
//        for (int i = 5; i >= 0; i--) {
//            LocalDate date = now.minusMonths(i);
//            statisticTimes.add(String.format("%d%02d", date.getYear(), date.getMonthValue()));
//        }

//        // 构建查询条件
//        LambdaQueryWrapper<AlOpermonEnergyConDjlydl> lqw = new LambdaQueryWrapper<>();
//        lqw.in(AlOpermonEnergyConDjlydl::getStatisticTime, statisticTimes)
//                .eq(AlOpermonEnergyConDjlydl::getDateType, 1)
//                .in(AlOpermonEnergyConDjlydl::getOrgCode, "134053", "134035")
//                .in(AlOpermonEnergyConDjlydl::getPowerGenerationType, "02", "03")
//                .isNotNull(AlOpermonEnergyConDjlydl::getElectricityConsumptio);
//
//        // 执行查询
//        List<AlOpermonEnergyConDjlydl> entityList = alOpermonEnergyConDjlydlMapper.selectList(lqw);

//        List<AlOpermonEnergyConDjlydl> monthData = new ArrayList<>();
//        for (AlOpermonEnergyConDjlydl entity : entityList) {
//            if (statTime.equals(entity.getStatisticTime())) {
//                monthData.add(entity);
//            }
//        }

//        // 转换为VO列表
//        List<AlProdoperStationPerVO> voList = statisticTimes.stream()
//                .map(statTime -> {
//                    int year = Integer.parseInt(statTime.substring(0, 4));
//                    int month = Integer.parseInt(statTime.substring(4, 6));
//
//                    // 过滤当前月份的数据
//                    List<AlOpermonEnergyConDjlydl> monthData = entityList.stream()
//                            .filter(entity -> statTime.equals(entity.getStatisticTime()))
//                            .collect(Collectors.toList());
//
//                    AlProdoperStationPerVO vo = new AlProdoperStationPerVO();
//                    vo.setYear(year);
//                    vo.setMonth(month);
//
//                    if (monthData.isEmpty()) {
//                        return vo;
//                    }
//
//                    // 按电厂和电力类型分组汇总
//                    Map<String, Map<String, BigDecimal>> summary = monthData.stream()
//                            .collect(Collectors.groupingBy(
//                                    AlOpermonEnergyConDjlydl::getOrgCode,
//                                    Collectors.groupingBy(
//                                            AlOpermonEnergyConDjlydl::getPowerGenerationType,
//                                            Collectors.reducing(
//                                                    BigDecimal.ZERO,
//                                                    entity -> entity.getElectricityConsumptio().divide(BigDecimal.valueOf(10000), 6, BigDecimal.ROUND_HALF_UP),
//                                                    BigDecimal::add
//                                            )
//                                    )
//                            ));
//
//                    // 提取数据
//                    Map<String, BigDecimal> huolinheData = summary.getOrDefault("134035", new HashMap<>());
//                    Map<String, BigDecimal> baiyinhuaData = summary.getOrDefault("134053", new HashMap<>());
//
//                    BigDecimal huolinheGreen = huolinheData.getOrDefault("2", BigDecimal.ZERO);
//                    BigDecimal huolinheFossil = huolinheData.getOrDefault("3", BigDecimal.ZERO);
//                    BigDecimal baiyinhuaGreen = baiyinhuaData.getOrDefault("2", BigDecimal.ZERO);
//                    BigDecimal baiyinhuaFossil = baiyinhuaData.getOrDefault("3", BigDecimal.ZERO);
//
//                    // 设置电量
//                    if (huolinheGreen.compareTo(BigDecimal.ZERO) > 0) vo.setHuolinheGreenPower(huolinheGreen);
//                    if (huolinheFossil.compareTo(BigDecimal.ZERO) > 0) vo.setHuolinheFossilPower(huolinheFossil);
//                    if (baiyinhuaGreen.compareTo(BigDecimal.ZERO) > 0) vo.setBaiyinhuaGreenPower(baiyinhuaGreen);
//                    if (baiyinhuaFossil.compareTo(BigDecimal.ZERO) > 0) vo.setBaiyinhuaFossilPower(baiyinhuaFossil);

//                    // 计算占比
//                    BigDecimal huolinheTotal = huolinheGreen.add(huolinheFossil);
//                    BigDecimal baiyinhuaTotal = baiyinhuaGreen.add(baiyinhuaFossil);
//
//                    if (huolinheTotal.compareTo(BigDecimal.ZERO) > 0) {
//                        vo.setHuolinheGreenRatio(huolinheGreen.divide(huolinheTotal, 4, BigDecimal.ROUND_HALF_UP)
//                                .multiply(BigDecimal.valueOf(100)));
//                    }
//                    if (baiyinhuaTotal.compareTo(BigDecimal.ZERO) > 0) {
//                        vo.setBaiyinhuaGreenRatio(baiyinhuaGreen.divide(baiyinhuaTotal, 4, BigDecimal.ROUND_HALF_UP)
//                                .multiply(BigDecimal.valueOf(100)));
//                    }

//                    return vo;
//                })
//                .collect(Collectors.toList());

        return voList;


//        // 获取当前日期
//        LocalDate currentDate = LocalDate.now();
//        LocalDate startDate = currentDate.minusMonths(11);
//
//        // 获取当前年月
//        String currentYearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
//
//        // 获取去年同期年月（减去1年）
//        String lastYearSameMonth = startDate.format(DateTimeFormatter.ofPattern("yyyyMM"));
//
//        // 查询最近12个月的数据
//        LambdaQueryWrapper<AlProdoperStationPer> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.ge(AlProdoperStationPer::getYear, startDate.getYear())
//                .between(AlProdoperStationPer::getStatisticTime, lastYearSameMonth,currentYearMonth)
//                .orderByDesc(AlProdoperStationPer::getStatisticTime);
//
//        List<AlProdoperStationPer> dataList = this.list(queryWrapper);
//
//        List<AlProdoperStationPerVO> result = new ArrayList<>();
//
//            // 按年月分组，取每月最后一天的数据
//            Map<String, AlProdoperStationPer> monthlyMaxData = new HashMap<>();
//            for (AlProdoperStationPer data : dataList) {
//                // 检查数据完整性，如果year、month、day任一为null，则跳过该条数据
//                if (data.getYear() == null || data.getMonth() == null || data.getDay() == null) {
//                    continue;
//                }
//
//                // 过滤出最近12个月的数据
//                LocalDate dataDate = LocalDate.of(data.getYear(), data.getMonth(), 1);
//                if (!dataDate.isBefore(startDate)) {
//                    String key = data.getYear() + "-" + data.getMonth();
//                    // 如果该月还没有数据，或者当前数据的day更大，则更新
//                    if (!monthlyMaxData.containsKey(key) ||
//                        monthlyMaxData.get(key).getDay() < data.getDay()) {
//                        monthlyMaxData.put(key, data);
//                    }
//                }
//            }
//
//            // 转换为VO并按年月排序
//            result = monthlyMaxData.values().stream()
//                    .sorted(Comparator.comparing(AlProdoperStationPer::getYear)
//                            .thenComparing(AlProdoperStationPer::getMonth))
//                    .map(data -> {
//                        AlProdoperStationPerVO vo = new AlProdoperStationPerVO();
//                        vo.setYear(data.getYear());
//                        vo.setMonth(data.getMonth());
//                        vo.setHuolinheGreenPower(data.getHuolinheGreenPower());
//                        vo.setBaiyinhuaGreenPower(data.getBaiyinhuaGreenPower());
//                        vo.setHuolinheFossilPower(data.getHuolinheFossilPower());
//                        vo.setBaiyinhuaFossilPower(data.getBaiyinhuaFossilPower());
//                        vo.setHuolinheGreenRatio(data.getHuolinheGreenRatio());
//                        vo.setBaiyinhuaGreenRatio(data.getBaiyinhuaGreenRatio());
//                        return vo;
//                    })
//                    .collect(Collectors.toList());
//
//        return result;

    }
    
//    /**
//     * 生成mock数据，覆盖最近12个月
//     */
//    private List<AlProdoperStationPerVO> generateMockData(LocalDate currentDate) {
//        List<AlProdoperStationPerVO> mockDataList = new ArrayList<>();
//
//        // 生成最近12个月的数据
//        for (int i = 11; i >= 0; i--) {
//            LocalDate targetDate = currentDate.minusMonths(i);
//            AlProdoperStationPerVO vo = new AlProdoperStationPerVO();
//
//            vo.setYear(targetDate.getYear());
//            vo.setMonth(targetDate.getMonthValue());
//
//            // 根据月份生成模拟数据，使数据有一定的波动性和真实性
//            // 霍林河绿电：8000-12000万千瓦时
//            BigDecimal huolinheGreen = BigDecimal.valueOf(8000 + (i * 300) + (i % 3) * 200);
//            // 霍林河火电：5000-8000万千瓦时
//            BigDecimal huolinheFossil = BigDecimal.valueOf(5000 + (i * 200) + (i % 4) * 150);
//
//            // 白音华绿电：7000-11000万千瓦时
//            BigDecimal baiyinhuaGreen = BigDecimal.valueOf(7000 + (i * 280) + (i % 5) * 180);
//            // 白音华火电：4500-7500万千瓦时
//            BigDecimal baiyinhuaFossil = BigDecimal.valueOf(4500 + (i * 220) + (i % 3) * 160);
//
//            vo.setHuolinheGreenPower(huolinheGreen);
//            vo.setHuolinheFossilPower(huolinheFossil);
//            vo.setBaiyinhuaGreenPower(baiyinhuaGreen);
//            vo.setBaiyinhuaFossilPower(baiyinhuaFossil);
//
//            // 计算绿电占比（绿电/（绿电+火电）* 100）
//            BigDecimal huolinheTotal = huolinheGreen.add(huolinheFossil);
//            BigDecimal huolinheRatio = huolinheGreen.divide(huolinheTotal, 4, RoundingMode.HALF_UP)
//                    .multiply(BigDecimal.valueOf(100))
//                    .setScale(2, RoundingMode.HALF_UP);
//
//            BigDecimal baiyinhuaTotal = baiyinhuaGreen.add(baiyinhuaFossil);
//            BigDecimal baiyinhuaRatio = baiyinhuaGreen.divide(baiyinhuaTotal, 4, RoundingMode.HALF_UP)
//                    .multiply(BigDecimal.valueOf(100))
//                    .setScale(2, RoundingMode.HALF_UP);
//
//            vo.setHuolinheGreenRatio(huolinheRatio);
//            vo.setBaiyinhuaGreenRatio(baiyinhuaRatio);
//
//            mockDataList.add(vo);
//        }
//
//        return mockDataList;
//    }

}
